package com.example.dakotanews.exception;

import com.example.dakotanews.dto.utils.ApiResponse;
import com.example.dakotanews.dto.utils.ResponseCode;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description 全局异常处理器，将控制层抛出的异常在此处统一处理。
 */

@ControllerAdvice(annotations = {RestController.class, Controller.class, Service.class})
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * @description 捕获SignatureException异常，响应代码。下同
     */
    @ExceptionHandler(SignatureException.class)
    public ApiResponse<String> handleSignatureException(SignatureException ex) {
        return new ApiResponse<>(ResponseCode.UNAUTHORIZED,
                "Invalid Token", "无效的令牌");
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public ApiResponse<String> handleExpiredJwtException(ExpiredJwtException ex) {
        return new ApiResponse<>(ResponseCode.UNAUTHORIZED,
                "Expired Token", "令牌已过期，请重新登录");
    }

    @ExceptionHandler(MalformedJwtException.class)
    public ApiResponse<String> handleMalformedJwtException(MalformedJwtException ex) {
        return new ApiResponse<>(ResponseCode.UNAUTHORIZED,
                "Invalid Token", "无效的令牌，json格式错误");
    }

    // 其他异常处理...
}